// pages/history/history.js
const app = getApp()

// 状态配置
const STATUS_CONFIG = {
  1: { // 正常
    name: '正常',
    icon: 'https://gitee.com/teajoy/image/raw/master/images/正常.png',
    color: '#34d399',
    statusIcon: 'icon-check'
  },
  2: { // 异常
    name: '异常',
    icon: 'https://gitee.com/teajoy/image/raw/master/images/异常.png',
    color: '#f87171',
    statusIcon: 'icon-warning'
  }
}

Page({
  data: {
    weekdays: ['日', '一', '二', '三', '四', '五', '六'],
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    days: [],
    selectedDate: '',
    selectedDateText: '',
    dayRecords: [],
    floatingBtnStyle: '' // 浮动按钮样式
  },

  onLoad() {
    // 默认选中今天
    const today = new Date()
    const todayStr = this.formatDate(today)
    
    this.setData({
      selectedDate: todayStr,
      selectedDateText: '今日'
    })
    
    this.initCalendar()
    this.loadDayRecords(todayStr)
  },

  onShow() {
    // 页面显示时刷新数据
    this.initCalendar()
    if (this.data.selectedDate) {
      this.loadDayRecords(this.data.selectedDate)
    }
  },

  // 初始化日历数据
  initCalendar() {
    const { year, month } = this.data
    const today = new Date()
    const todayStr = this.formatDate(today)
    
    // 获取当月第一天是星期几
    const firstDay = new Date(year, month - 1, 1).getDay()
    // 获取当月天数
    const daysInMonth = new Date(year, month, 0).getDate()
    // 获取上月天数
    const daysInPrevMonth = new Date(year, month - 1, 0).getDate()

    const days = []
    
    // 上月日期
    for (let i = firstDay - 1; i >= 0; i--) {
      const day = daysInPrevMonth - i
      const date = this.formatDate(new Date(year, month - 2, day))
      days.push({
        day,
        date,
        current: false,
        selected: date === this.data.selectedDate,
        today: date === todayStr
      })
    }
    
    // 当月日期
    for (let i = 1; i <= daysInMonth; i++) {
      const date = this.formatDate(new Date(year, month - 1, i))
      days.push({
        day: i,
        date,
        current: true,
        selected: date === this.data.selectedDate,
        today: date === todayStr
      })
    }
    
    // 下月日期
    const remainingDays = 42 - days.length // 保持6行
    for (let i = 1; i <= remainingDays; i++) {
      const date = this.formatDate(new Date(year, month, i))
      days.push({
        day: i,
        date,
        current: false,
        selected: date === this.data.selectedDate,
        today: date === todayStr
      })
    }

    // 获取所有记录日期
    const records = wx.getStorageSync('poopRecords') || []
    const recordDates = new Set(records.map(r => r.date))
    
    // 添加记录标记
    days.forEach(day => {
      day.hasRecord = recordDates.has(day.date)
      if (day.hasRecord) {
        const record = records.find(r => r.date === day.date)
        day.markerColor = record?.statusColor || 'pink'
      }
    })

    this.setData({ days })
  },

  // 选择日期
  selectDate(e) {
    const date = e.currentTarget.dataset.date
    const today = this.formatDate(new Date())
    
    // 更新选中状态
    const days = this.data.days.map(day => ({
      ...day,
      selected: day.date === date
    }))
    
    this.setData({
      selectedDate: date,
      selectedDateText: date === today ? '今日' : this.formatDateText(date),
      days
    })
    
    this.loadDayRecords(date)
  },

  // 格式化日期：YYYY-MM-DD
  formatDate(date) {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  },

  // 格式化日期显示文本
  formatDateText(dateStr) {
    const date = new Date(dateStr)
    return `${date.getMonth() + 1}月${date.getDate()}日`
  },

  // 上个月
  prevMonth() {
    let { year, month } = this.data
    if (month === 1) {
      year--
      month = 12
    } else {
      month--
    }
    this.setData({ year, month })
    this.initCalendar()
  },

  // 下个月
  nextMonth() {
    let { year, month } = this.data
    if (month === 12) {
      year++
      month = 1
    } else {
      month++
    }
    this.setData({ year, month })
    this.initCalendar()
  },

  // 加载当天记录
  loadDayRecords(date) {
    // 从本地存储获取数据
    const allRecords = wx.getStorageSync('poopRecords') || []
    
    // 确保时间格式跨平台兼容
    const dayRecords = allRecords
      .filter(record => record.date === date)
      .map(record => {
        // 获取类型信息
        const statusInfo = STATUS_CONFIG[record.typeId] || STATUS_CONFIG[1]
        
        // 处理时间，确保包含秒数
        let timeWithSeconds = record.time || '00:00:00' // 添加默认值，防止 undefined
        if (!timeWithSeconds) {
          timeWithSeconds = '00:00:00' // 如果 time 不存在，则使用默认值
        } else if (!timeWithSeconds.includes(':')) {
          timeWithSeconds = timeWithSeconds + ':00'
        } else if (timeWithSeconds.split(':').length === 2) {
          timeWithSeconds = timeWithSeconds + ':00'
        }
        
        // 解析时间字符串为日期对象（兼容处理）
        const [hours, minutes, seconds] = timeWithSeconds.split(':').map(Number)
        const timestamp = new Date(date).setHours(hours, minutes, seconds)
        
        // 格式化时长显示
        let durationText = ''
        if (record.durationText) {
          // 如果有预格式化的时长文本，直接使用
          durationText = record.durationText
        } else if (typeof record.duration === 'number' || typeof record.durationSeconds === 'number') {
          // 如果有原始的分钟和秒数数据
          const minutes = record.duration || 0
          const seconds = record.durationSeconds || 0
          durationText = `${minutes}分${seconds}秒`
        } else {
          // 兼容旧数据，将duration作为分钟数
          const minutes = parseInt(record.duration) || 0
          durationText = `${minutes}分0秒`
        }
        
        // 处理记录数据
        
        return {
          id: record.id,
          type: statusInfo.name,
          rawTime: timestamp, // 用于排序
          time: timeWithSeconds, // 使用带秒数的时间
          color: statusInfo.color,
          status: statusInfo.name,
          statusIcon: statusInfo.statusIcon,
          statusColor: statusInfo.color,
          poopIcon: statusInfo.icon,
          duration: durationText,
          note: record.note || ''
        }
      })
      .sort((a, b) => b.rawTime - a.rawTime) // 使用时间戳倒序排序
    
    this.setData({ dayRecords })
  },

  // 格式化时间显示（24小时制）
  formatTime(timeStr) {
    const [hours, minutes, seconds] = timeStr.split(':')
    const hour = String(hours).padStart(2, '0')
    const minute = String(minutes).padStart(2, '0')
    const second = String(seconds).padStart(2, '0')
    return `${hour}:${minute}:${second}`
  },

  // 查看详情
  onViewDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/packageA/pages/detail/detail?id=${id}`
    })
  },

  // 跳转到补卡页面
  goToMakeup() {
    // 如果是拖动操作，不执行跳转
    if (this.isDragging) {
      this.isDragging = false
      return
    }
    
    wx.navigateTo({
      url: '/packageA/pages/makeup/makeup'
    })
  },

  // 补卡按钮拖动相关
  onFloatingBtnTouchStart(e) {
    this.startX = e.touches[0].clientX
    this.startY = e.touches[0].clientY
    this.isDragging = false
  },

  onFloatingBtnTouchMove(e) {
    const moveX = e.touches[0].clientX - this.startX
    const moveY = e.touches[0].clientY - this.startY
    
    // 判断是否为拖动（移动距离超过10px）
    if (Math.abs(moveX) > 10 || Math.abs(moveY) > 10) {
      this.isDragging = true
      
      // 获取屏幕尺寸
      const systemInfo = wx.getSystemInfoSync()
      const screenWidth = systemInfo.windowWidth
      const screenHeight = systemInfo.windowHeight
      
      // 计算新位置（rpx转px，1rpx = 0.5px）
      let newX = e.touches[0].clientX - 30 // 按钮宽度的一半(60rpx = 30px)
      let newY = e.touches[0].clientY - 30 // 按钮高度的一半
      
      // 边界限制
      newX = Math.max(15, Math.min(newX, screenWidth - 75)) // 留15px边距
      newY = Math.max(15, Math.min(newY, screenHeight - 75))
      
      // 更新按钮位置
      this.setData({
        floatingBtnStyle: `left: ${newX}px; top: ${newY}px; right: auto; bottom: auto;`
      })
    }
  },

  onFloatingBtnTouchEnd(e) {
    // 拖动结束后的处理
    if (this.isDragging) {
      // 可以添加吸附到边缘的逻辑
      const systemInfo = wx.getSystemInfoSync()
      const screenWidth = systemInfo.windowWidth
      const currentX = e.changedTouches[0].clientX - 30
      
      // 吸附到左右边缘
      let finalX = currentX
      if (currentX < screenWidth / 2) {
        finalX = 15 // 吸附到左边
      } else {
        finalX = screenWidth - 75 // 吸附到右边
      }
      
      this.setData({
        floatingBtnStyle: `left: ${finalX}px; top: ${e.changedTouches[0].clientY - 30}px; right: auto; bottom: auto; transition: left 0.3s ease;`
      })
      
      // 延迟重置拖动状态，避免立即触发点击
      setTimeout(() => {
        this.isDragging = false
      }, 100)
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '我的健康记录日历',
      path: '/pages/history/history',
      imageUrl: 'https://gitee.com/teajoy/image/raw/master/images/share-cover.png'
    }
  }
})